package com.by_man.presenter.module_health_records.upload_health_records;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Process;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.module_health_records.image.AllImages;
import com.by_man.presenter.module_health_records.image.BitmapManager;
import com.by_man.presenter.module_health_records.image.BucketImgList;
import com.by_man.presenter.module_health_records.image.ImageInfo;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * 图片选择页面
 * Created by man on 2017-02-28.
 */
public class ChosePhotoActivity extends AppCompatActivity {
    private ArrayList<ImageInfo> allImgs;
    private AllImages imgManager;
    private Button ok;
    private Button preview;
    private GridView gridView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chose_photo);
        // 动态申请权限
        int permission = checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, Process.myPid(), Process.myUid());
        if (permission == PackageManager.PERMISSION_DENIED) { // 如果没有权限。请求权限
            Log.d("Permission", "没有访问权限！");
            //enforcePermission();
            grantUriPermission(getPackageName(), MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            permission = checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, Process.myPid(), Process.myUid());
        }
        BitmapManager.setCacheMaxSize(10 * 1024 * 1024);
        initImgData();
        initView();
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(this, UploadHealthRecordsActivity.class);
//            startActivity(intent);
//        }
//        return super.onKeyDown(keyCode, event);
//    }

//    protected void onRestart()
//    {
//        super.onRestart();
//        Intent intent=new Intent(this,GestureLockActivity.class);
//        intent.putExtra("class",this.getClass().getName());
//        intent.putExtra("position", 0);
//        startActivity(intent);
//    }

    private void initView() {
        Button album = (Button) findViewById(R.id.back);
        Button cancel = (Button) findViewById(R.id.cancel);
        preview = (Button) findViewById(R.id.preview);
        ok = (Button) findViewById(R.id.ok_button);
        gridView = (GridView) findViewById(R.id.myGrid);
//        TextView textView = (TextView) findViewById(R.id.myText);
//        gridView.setEmptyView(textView);
        GridViewAdapter adapter = new GridViewAdapter(BitmapManager.images, allImgs, this);
        gridView.setAdapter(adapter);

        album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ChosePhotoActivity.this, AlbumActivity.class);
                startActivity(intent);
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BitmapManager.images.clear();
//                Intent intent = new Intent(ChosePhotoActivity.this, UploadHealthRecordsActivity.class);
//                startActivity(intent);
                onBackPressed();
            }
        });
        preview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ChosePhotoActivity.this, PhotoGalleryActivity.class);
                startActivity(intent);
            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ChosePhotoActivity.this, UploadHealthRecordsActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

    // 初始化图片信息
    private void initImgData() {
        imgManager = AllImages.getInstance();
        imgManager.init(getApplication());
        ArrayList<BucketImgList> list = imgManager.getAllImgs(false);
        allImgs = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            allImgs.addAll(list.get(i).imgList);
        }
    }

//    @Override
//    protected void onPause() {
//        super.onPause();
//        gridView.setAdapter(null);
//        gridView.setOnItemClickListener(null);
//        BitmapManager.setCacheMaxSize(2*1024*1024);
//    }
}

// 自定义GridView的Adapter
class GridViewAdapter extends BaseAdapter {
    private ArrayList<ImageInfo> selectedImgs;
    private ArrayList<ImageInfo> allImgs;
    private AppCompatActivity activity;
    //private GridView mGridView;
    private Button ok;
    private Button preview;
    private LayoutInflater layoutInflater;
    public GridViewAdapter(ArrayList<ImageInfo> lists,ArrayList<ImageInfo> allImgs,AppCompatActivity activity) {
        selectedImgs = lists;
        this.allImgs = allImgs;
        this.activity = activity;
        //mGridView = (GridView) activity.findViewById(R.id.myGrid);
        preview = (Button) activity.findViewById(R.id.preview);
        ok = (Button) activity.findViewById(R.id.ok_button);
        layoutInflater = LayoutInflater.from(activity);
    }

    private void getWarn() {
        SharedApplication.showToast(activity, "只能选择" + BitmapManager.max + "张图！");
    }

    private void setButton() {
        if (BitmapManager.images.size() > 0) {
            preview.setPressed(true);
            ok.setPressed(true);
            preview.setClickable(true);
            ok.setClickable(true);
            preview.setTextColor(Color.WHITE);
            ok.setTextColor(Color.WHITE);
            ok.setText("ok" + "(" + selectedImgs.size() + "/"
                    + BitmapManager.max + ")");
        } else {
            preview.setPressed(false);
            ok.setPressed(false);
            preview.setClickable(false);
            ok.setClickable(false);
            preview.setTextColor(Color.parseColor("#E1E0DE"));
            ok.setTextColor(Color.parseColor("#E1E0DE"));
            ok.setText("ok" + "(" + selectedImgs.size() + "/"
                    + BitmapManager.max + ")");
        }
    }

    @Override
    public int getCount() {
        return allImgs.size();
    }

    @Override
    public Object getItem(int position) {
        return allImgs.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (null == convertView) {
            viewHolder = new ViewHolder();
            convertView = layoutInflater.inflate(R.layout.item_grid_view_chose_photo, parent, false);
            viewHolder.imageView = (ImageView) convertView.findViewById(R.id.image_view);
            viewHolder.toggleButton = (ToggleButton) convertView.findViewById(R.id.toggle_button);
            viewHolder.choosetoggle = (Button) convertView.findViewById(R.id.choosedbt);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        // 异步加载图片
        loadBitmap(position,viewHolder.imageView);
        //String path = allImgs.get(position).imagePath;
        //viewHolder.imageView.setTag(path);          // 确定imageview用
        /*
        Bitmap bitmap = BitmapManager.getBitmap(path);
        if (null == bitmap) {
            viewHolder.imageView.setImageResource(R.drawable.plugin_camera_no_pictures);
        } else {
            viewHolder.imageView.setImageBitmap(bitmap);
        }
        */

        // 为button设定监听
        ArrayList<Object> tags = new ArrayList<>();
        tags.add(position);
        tags.add(viewHolder.choosetoggle);
        viewHolder.toggleButton.setTag(tags);
        viewHolder.choosetoggle.setTag(position);
        setButton();                                // 设置button
        viewHolder.toggleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToggleButton btn = (ToggleButton) view;
                ArrayList<Object> tags = (ArrayList<Object>) btn.getTag();
                int position = (int)tags.get(0);
                Button choosebtn = (Button) tags.get(1);
                if (allImgs != null && position < allImgs.size()) {
                    if (selectedImgs.size() >= BitmapManager.max) {     // 图片以选够
                        btn.setChecked(false);
                        choosebtn.setVisibility(View.GONE);
                        getWarn();
                    }

                    // 这块逻辑有点难
                    if (btn.isChecked()) {
                        choosebtn.setVisibility(View.VISIBLE);
                        selectedImgs.add(allImgs.get(position));
                        //ok.setText("ok" + "(" + selectedImgs.size() + "/"
                        //  + BitmapManager.max + ")");
                    } else {
                        selectedImgs.remove(allImgs.get(position));
                        choosebtn.setVisibility(View.GONE);
                        //ok.setText("ok" + "(" + selectedImgs.size() + "/"
                        //        + BitmapManager.max + ")");
                    }
                    setButton();
                }
            }
        });
        return convertView;
    }

    // 封装View
    private class ViewHolder {
        public ImageView imageView;
        public ToggleButton toggleButton;
        public Button choosetoggle;
    }

    /*************************************************************************
     * 异步加载图片所用的类与方法
     *************************************************************************/

    // 为每个ImageView保存相应的异步任务信息，采用弱应用，避免系统无法回收ImageView
    class AsyncInfo {
        private int position;
        private final WeakReference<AsyncImageLoader> imageLoaderWeakReference;

        public AsyncInfo(int position, AsyncImageLoader imageLoader) {
            this.position = position;
            imageLoaderWeakReference = new WeakReference<AsyncImageLoader>(imageLoader);
        }

        public AsyncImageLoader getImageLoader() {
            return imageLoaderWeakReference.get();
        }
    }

    // 异步加载图片
    class AsyncImageLoader extends AsyncTask<Integer, Void, Bitmap> {
        public Integer position = null;
        private final WeakReference<ImageView> imageViewWeakReference;
        public AsyncImageLoader(ImageView imageView) {
            imageViewWeakReference = new WeakReference<ImageView>(imageView);
        }

        @Override
        protected Bitmap doInBackground(Integer... params) {
            position = params[0];
            String thumbnailPath = allImgs.get(position).thumbnailPath;
            String imgPath = allImgs.get(position).imagePath;
            Bitmap bitmap;
            if (null == thumbnailPath)
                bitmap = BitmapManager.getCompressBitmap(imgPath, 100, 100);
            else {
                // bitmap加载缩略图可能为空
                bitmap = BitmapManager.getCompressBitmap(thumbnailPath, 100, 100);
                if (null == bitmap) {
                    bitmap = BitmapManager.getCompressBitmap(imgPath, 100, 100);
                }
            }
            BitmapManager.putBitmap(imgPath,bitmap);
            return bitmap;
        }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (imageViewWeakReference != null && bitmap != null) {
            final ImageView imageView = imageViewWeakReference.get();
            imageView.setImageBitmap(bitmap);
        }
    }
}

    // 取消之前的加载任务
    public static boolean cancelPotentialWork(int data, ImageView imageView) {
        final AsyncImageLoader imageLoader = getAsyncImageLoader(imageView);
        if (imageLoader != null) {
            // 注意可能有空指针
            //final int position = imageLoader.position;
            //Log.d("Position", "" + position);
            if (imageLoader.position != null) {
                final int position = imageLoader.position;
                if (position != data) {     // 不等，取消之前的加载任务
                    imageLoader.cancel(true);
                } else {
                    return false;
                }
            } else {
                // 取消
                imageLoader.cancel(true);
            }
        }
        return true;
    }

    // 取出与ImageView相关联的异步任务
    public static AsyncImageLoader getAsyncImageLoader(ImageView imageView) {
        if(imageView != null) {
            final AsyncInfo info = (AsyncInfo) imageView.getTag();
            if (info != null) {
                return info.getImageLoader();
            }
        }
        return null;
    }

    public void loadBitmap(int position, ImageView imageView) {
        if (cancelPotentialWork(position,imageView)) {
            final Bitmap bitmap = BitmapManager.getBitmap(allImgs.get(position).imagePath);
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            } else {
                final AsyncImageLoader imageLoader = new AsyncImageLoader(imageView);
                AsyncInfo asyncInfo = new AsyncInfo(position, imageLoader);
                imageView.setTag(asyncInfo);                    // 设置关联信息
                imageView.setImageResource(R.drawable.plugin_camera_no_pictures);
                imageLoader.execute(position);
            }
        }
    }

}
